
import re
import os
import sys
import shutil
import argparse

def get_args():
    parser = argparse.ArgumentParser(description=u'获取参数')
    parser.add_argument('-i', '--input',  
                        help=u'指定输入文件')
    parser.add_argument('-o', '--output',
                        help=u'指定输出文件，默认merge')
    parser.add_argument('-n', '--name',
                        help=u'指定固件版本文件')
    parser.add_argument('-p', '--path',
                        help=u'指定输出路径')
    args = parser.parse_args()
    # print(args)
    return args

def get_name(fname):
    import re
    # file_version = "VersionDefine.h"
    firmware_name = None

    if not fname:
        return None
    fname = fname.strip()
    if not os.path.isfile(fname):
        txt = "ERROR: File not found: %s" % fname
        print(txt) 
        return None

    with open(fname, 'r') as fin:
        for line in fin.readlines():
            m = re.match('#define FIRMWARE_VERSION', line)
            if m :
                s = re.search(r'(\")(\S*)(\")', line)
                if s :
                    name = s.groups()[1].replace('-', '_')
                    firmware_name = name
                break

    return firmware_name

def main():
    args = get_args()
    # print(args)
    if not args.input:
        print('Input file is not specified')
        return 1

    input_file = args.input.strip()
    if not os.path.isfile(input_file):
        txt = "ERROR: File not found: %s" % input_file
        print(txt)
        return 2
    
    output = args.output
    if not output:
        name = get_name(args.name)
        if name :
            output = name + '.hex'
        else:
            output = os.path.split(input_file)[1]
            
        if args.path :
            if not os.path.exists(args.path):
                os.makedirs(args.path)
            output_file = os.path.join(args.path, output)
        else:
            output_file = output
    else:
        output_file = output.strip()
        
    try:
        if os.path.isfile(output_file):
            os.remove(output_file)
        shutil.move(input_file, output_file)
    except OSError:
        e = sys.exc_info()[1]     # current exception
        sys.stderr.write(str(e)+"\n")
        return 2
        
    return 0

if __name__ == '__main__' :
    sys.exit(main())
        
    